package pl.edu.pw.perg.compinfodb.datamodel;

import java.util.ArrayList;
import java.util.List;

import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;

import pl.edu.pw.perg.compinfodb.entities.VirtualElement;

public class LogicalDetailsTableModel implements TableModel,
		IStructureTreeSelectionListener {

	private List<TableModelListener> listeners = new ArrayList<TableModelListener>();
	private String[] columnNames = { "Property", "Value" };
	private VirtualElement selected;
	
	private List<String> propertyList = new ArrayList<String>();
	private List<String> valueList = new ArrayList<String>();

	public LogicalDetailsTableModel(){
		propertyList.add("Name");
		propertyList.add("Type");
		propertyList.add("Parent's Name");
		propertyList.add("Location");
		propertyList.add("Input Connectors");
		propertyList.add("Output Connectors");
		
	}
	
	public void addTableModelListener(TableModelListener l) {
		listeners.add(l);
	}

	public Class<?> getColumnClass(int columnIndex) {
		return String.class;
	}

	public int getColumnCount() {
		return 2;
	}

	public String getColumnName(int columnIndex) {
		return columnNames[columnIndex];
	}

	public int getRowCount() {
		// type, name, parent name, location
		return 4;
	}

	public Object getValueAt(int rowIndex, int columnIndex) {
		if(columnIndex == 0)
			return propertyList.get(rowIndex);
		else if(selected != null && columnIndex == 1){
			if(rowIndex == 0)
				return selected.getName();
			else if (rowIndex == 1) 
				return selected.getElementType().getTypeName();
			else if(rowIndex == 2)
				if(selected.getParent() != null)
					return selected.getParent().getName();
				else return "";
			else if(rowIndex == 3)
				return (selected.getLocation() != -1) ? selected.getLocation(): "N/A";		
			else if(rowIndex == 4)
				return selected.getElementType().getInputConnectorsNr();
			else if(rowIndex == 5)
				return selected.getElementType().getOutputConnectorsNr();
        			
		}
		else if (selected == null)
			return "";
		throw new IndexOutOfBoundsException("Invalid row/column nr"); 
	}

	public boolean isCellEditable(int rowIndex, int columnIndex) {
		return false;
	}

	public void removeTableModelListener(TableModelListener l) {
		listeners.remove(l);

	}

	public void setValueAt(Object value, int rowIndex, int columnIndex) {
		throw new UnsupportedOperationException(
				"This table don't allows changes");

	}

	public void selectionChanged(VirtualElement ve) {
		selected = ve;
		for (TableModelListener tml : listeners) {
			tml.tableChanged(new TableModelEvent(this));
		}

	}

}
